<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="100px">

      <el-form-item label="档案标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入档案标题"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证书类型" prop="certificateType">
        <el-select v-model="queryParams.certificateType" placeholder="请选择证书类型" clearable>
          <el-option label="学位证书" value="学位证书" />
          <el-option label="学历证书" value="学历证书" />
          <el-option label="语言证书" value="语言证书" />
          <el-option label="居民身份证" value="居民身份证" />
          <el-option label="教师资格证" value="教师资格证" />
          <el-option label="其它证书" value="其它证书" />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出</el-button>
      </el-form-item>
    </el-form>



    <el-table v-loading="loading" :data="certificateinfoList" @selection-change="handleSelectionChange" ref="CertificationTable">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="唯一标识" align="center" prop="id" />-->
      <el-table-column label="上传者" align="center" prop="nickName" />
      <el-table-column label="档案标题" align="center" prop="title" />
      <el-table-column label="证书类型" align="center" prop="certificateType" />

      <el-table-column label="获得时间" align="center" prop="obtainTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.obtainTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="Download"
              @click="download(scope.row)"
              :disabled="!scope.row.pdfUrl"
          >下载</el-button>
          <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['result:certificateinfo:edit']"
          >详情</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改档案资料上传对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="档案标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入档案标题" />
        </el-form-item>
        <el-form-item label="获得时间" prop="obtainTime">
          <el-date-picker
              v-model="form.obtainTime"
              type="date"
              placeholder="选择获得时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="证书编号" prop="certificateNumber">
          <el-input v-model="form.certificateNumber" placeholder="请输入证书编号" />
        </el-form-item>
        <el-form-item label="授予机构" prop="issuingInstitution">
          <el-input v-model="form.issuingInstitution" placeholder="请输入授予机构" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="关联课题" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入关联课题" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <certification-export :files="exportData" v-model="showExportDialog"></certification-export>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { treeselect } from "@/api/system/dept";
import CertificationExport from "@/components/result/ExportDialog/certificationExport.vue";
import { listCertificateinfo, getCertificateinfo, delCertificateinfo, addCertificateinfo, updateCertificateinfo, getCertificateinfoByIds } from "@/api/result/certificateinfo"
import {useRouter} from "vue-router";
import {listPostOptions} from "../../../api/system/post";
import {getRoleOptions} from "../../../api/system/role";

const router = useRouter()
const queryFormRef = ref(null)
const formRef = ref(null)
const loading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const open = ref(false)
const certificateinfoList = ref([])
const deptName = ref("");
const deptOptions = ref(undefined);
const postOptions = ref([]);
const roleOptions = ref([]);
const showExportDialog = ref(false);
const exportData = ref([]);
const CertificationTable=ref(null)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: null,
  certificateType: null,
  obtainTime: null,
  certificateNumber: null,
  issuingInstitution: null,
  remarks: null,
  projectId: null,
  syncStatus: null,
  createdAt: null,
  updatedAt: null,
  pdfUrl: null,
  userId: null,
  deptId: null,
  postIds: [],
  roleIds: [],
  queryPublishDate: [],
})

const form = reactive({
  id: null,
  title: null,
  certificateType: null,
  obtainTime: null,
  certificateNumber: null,
  issuingInstitution: null,
  remarks: null,
  projectId: null,
  syncStatus: "0",
  createdAt: null,
  updatedAt: null,
  pdfUrl: null,
  userId: null,
  postIds: [],
  roleIds: [],
})

const rules = {
  title: [
    { required: true, message: "档案标题不能为空", trigger: "blur" }
  ],
  certificateType: [
    { required: true, message: "证书类型不能为空", trigger: "change" }
  ],
  obtainTime: [
    { required: true, message: "获得时间不能为空", trigger: "blur" }
  ],
}
const download = (row) => {
  if (row.pdfUrl) {
    console.log('下载:', row.pdfUrl);
    window.open(row.pdfUrl, '_blank');
  } else {
    ElMessage.warning('该报告没有可下载的PDF文件');
  }
};
onMounted(() => {

  getList()
})
/** 查询系部下拉树结构 */
function getDeptTree() {
  treeselect().then(response => {
    deptOptions.value = response.data;
  });
  // deptTreeSelect().then(response => {
  //   deptOptions.value = response.data;
  // });
};
/** 查询档案资料上传列表 */
function getList() {
  loading.value = true
  listCertificateinfo(queryParams).then(response => {
    certificateinfoList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.id = null
  form.title = null
  form.certificateType = null
  form.obtainTime = null
  form.certificateNumber = null
  form.issuingInstitution = null
  form.remarks = null
  form.projectId = null
  form.syncStatus = "0"
  form.createdAt = null
  form.updatedAt = null
  form.pdfUrl = null
  form.userId = null
  formRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  queryParams.postIds = [];
  queryParams.roleIds = [];
  queryParams.queryPublishDate = [];
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加档案资料上传"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log('编辑:', row.id);
  router.push({ path: '/main/certification/edit', query: { id: row.id } });
  // reset()
  // const id = row.id || ids.value
  // getCertificateinfo(id).then(response => {
  //   Object.assign(form, response.data)
  //   open.value = true
  //   title.value = "修改档案资料上传"
  // })
}

/** 提交按钮 */
function submitForm() {
  formRef.value?.validate(valid => {
    if (valid) {
      if (form.id != null) {
        updateCertificateinfo(form).then(response => {
          ElMessage.success("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCertificateinfo(form).then(response => {
          ElMessage.success("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const certificateIds = row.id || ids.value
  ElMessageBox.confirm('是否确认删除档案资料上传编号为"' + certificateIds + '"的数据项？').then(() => {
    return delCertificateinfo(certificateIds)
  }).then(() => {
    getList()
    ElMessage.success("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
async function handleExport() {
  const selectedRows = CertificationTable.value.getSelectionRows();
  if (selectedRows.length === 0) {
    ElMessage.warning('请选择要导出的档案资料');
    return;
  }

  // 提取选中的 id
  const selectedIds = selectedRows.map(item => item.id);

  // 获得具体信息
  const res = await getCertificateinfoByIds(selectedIds);
  console.log('获取到的导出数据:', res);
  if (res.code === 200 && res.data) {
    // 更新 exportData
    exportData.value = Array.isArray(res.data) ? res.data : [res.data];
    // 打开导出对话框
    showExportDialog.value = true;
  } else {
    ElMessage.error('获取数据失败');
  }
}

</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
